package com.bf.electroplating.util.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.InflowManagement;
import com.bf.electroplating.pojo.entity.SewageWarningConfig;
import com.bf.electroplating.pojo.enums.DicTypeEnums;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.IInflowManagementService;
import com.bf.electroplating.service.ISewageWarningConfigService;
import com.bf.electroplating.service.PubParamDictionaryService;
import com.bf.electroplating.service.impl.PubParamDictionaryServiceImpl;
import com.bf.electroplating.service.impl.SewageWarningConfigServiceImpl;
import com.bf.electroplating.util.easyexcel.excel.warning.WarningDataExcel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.excel.cache.Ehcache.BATCH_COUNT;

/**
 * 预警数据导入监听器
 */
@Slf4j
@Component
public class WarningDataExcelListener extends AnalysisEventListener<WarningDataExcel> {

    Set<String> companySet = new HashSet<>();

    List<WarningDataExcel> dataList = new ArrayList<>();

    private ComCompanyService comCompanyService;

    private IInflowManagementService inflowManagementService;

    private ISewageWarningConfigService sewageWarningConfigService;

    private PubParamDictionaryService pubParamDictionaryService;

    public WarningDataExcelListener(ComCompanyService  comCompanyService, ISewageWarningConfigService sewageWarningConfigService, IInflowManagementService inflowManagementService,PubParamDictionaryService pubParamDictionaryService) {
        this.comCompanyService = comCompanyService;
        this.sewageWarningConfigService = sewageWarningConfigService;
        this.inflowManagementService = inflowManagementService;
        this.pubParamDictionaryService = pubParamDictionaryService;
    }
    /**
     * 读取excel每行数据
     */
    @Override
    public void invoke(WarningDataExcel warningDataExcel, AnalysisContext analysisContext) {
        // 获取当前行号
        int currentRowNum = analysisContext.readSheetHolder().getRowIndex();
        
        // 数据校验
        if (warningDataExcel != null) {
            // 记录每行数据
            log.info("第{}行数据: 企业名称={}, 废水类型={}, 检测因子={}, 含量={}{}, 检测时间={}, 预警等级={}", 
                currentRowNum + 1,
                warningDataExcel.getCompanyName(),
                warningDataExcel.getWastewaterType(),
                warningDataExcel.getDetectionFactor(),
                warningDataExcel.getContent()
//                warningDataExcel.getUnit(),
//                warningDataExcel.getDetectionTime(),
//                warningDataExcel.getWarningLevel()
            );
            
            dataList.add(warningDataExcel);
        }

        // 达到BATCH_COUNT了，需要去处理一次数据，防止数据几万条数据在内存，容易OOM
//        if (dataList.size() >= BATCH_COUNT) {
//            processData();
            // 处理完成清理 list
//            dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
//        }

    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//        processData();
        log.info("所有数据解析完成，共处理{}条预警数据", getTotalCount());
        List<ComCompany> comCompanies = comCompanyService
                .list(new LambdaQueryWrapper<ComCompany>().in(ComCompany::getCompanyName, dataList.stream()
                        .map(WarningDataExcel::getCompanyName).toList()));
        Map<String,ComCompany> stringComCompanyMap=comCompanies.stream().collect(Collectors.toMap(i->i.getCompanyName(),i->i));
        Map<String,SewageWarningConfig> stringInflowManagementMap=new HashMap<>();
        for (WarningDataExcel warningDataExcel : dataList) {
            if (StringUtils.isEmpty(warningDataExcel.getCompanyName())) {
                continue;
            }
            ComCompany comCompany = stringComCompanyMap.get(warningDataExcel.getCompanyName());
            String wasteType=pubParamDictionaryService.getCodeByModuleAndName(DicTypeEnums.FSLX.getCode(),warningDataExcel.getWastewaterType());
            String key=comCompany+wasteType;

            if (stringInflowManagementMap.containsKey(key)) {
                SewageWarningConfig inflowManagement = stringInflowManagementMap.get(key);
                switch (warningDataExcel.getDetectionFactor()){
                    case "总镍":
                        inflowManagement.setMonitorTotalNickel("1");
                        inflowManagement.setTotalNickelThreshold(new BigDecimal(warningDataExcel.getContent().replace("mg/L","")));
                        break;
                    case "六价铬":
                        inflowManagement.setMonitorHexavalentChromium("1");
                        inflowManagement.setHexavalentChromiumThreshold(new BigDecimal(warningDataExcel.getContent().replace("mg/L","")));
                        break;
                    case "总铬":
                        inflowManagement.setMonitorTotalChromium("1");
                        inflowManagement.setTotalChromiumThreshold(new BigDecimal(warningDataExcel.getContent().replace("mg/L","")));
                        break;
                 }
            }else {
                SewageWarningConfig inflowManagement = new SewageWarningConfig();
                inflowManagement.setCompanyName(comCompany.getCompanyName());
                inflowManagement.setCompanyId(comCompany.getId());
                inflowManagement.setWasteWaterType(wasteType);
//                inflowManagement.setMonitorHexavalentChromium("1");
//                inflowManagement.setMonitorTotalNickel("1");
//                inflowManagement.setMonitorTotalChromium("1");
//                inflowManagement.setWasteWaterType(wasteType);
//                inflowManagement.setHexavalentChromiumThreshold(new BigDecimal(10));
//                inflowManagement.setTotalNickelThreshold(new BigDecimal(30));
//                inflowManagement.setTotalChromiumThreshold(new BigDecimal(20));
//                inflowManagement.setCreateTime(LocalDate.now());
//                inflowManagement.setUpdateTime(LocalDate.now());
//                inflowManagement.setDetectionDate(LocalDate.now());
                inflowManagement.setDelFlag("0");
                switch (warningDataExcel.getDetectionFactor()){
                    case "总镍":
                        inflowManagement.setMonitorTotalNickel("1");
                        inflowManagement.setTotalNickelThreshold(new BigDecimal(warningDataExcel.getContent().replace("mg/L","")));
                        break;
                    case "六价铬":
                        inflowManagement.setMonitorHexavalentChromium("1");
                        inflowManagement.setHexavalentChromiumThreshold(new BigDecimal(warningDataExcel.getContent().replace("mg/L","")));
                        break;
                    case "总铬":
                        inflowManagement.setMonitorTotalChromium("1");
                        inflowManagement.setTotalChromiumThreshold(new BigDecimal(warningDataExcel.getContent().replace("mg/L","")));
                        break;
                }
                stringInflowManagementMap.put(key, inflowManagement);
            }
        }
        List<SewageWarningConfig> inflowManagementList = stringInflowManagementMap.values().stream().collect(Collectors.toList());
        sewageWarningConfigService.saveBatch(inflowManagementList);
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("Excel表头信息: {}", headMap);
    }

    /**
     * 处理数据（这里只做日志输出，不保存到数据库）
     */
    private void processData() {
        log.info("开始处理{}条预警数据...", dataList.size());

        List<String> companyNameList = dataList.stream().map(WarningDataExcel::getCompanyName).distinct().toList();
       if (!CollectionUtils.isEmpty(companyNameList)&& !StringUtils.isEmpty(companyNameList.get(0))) {

//           for (ComCompany comCompany : comCompanies) {
//               if (!companySet.contains(comCompany.getCompanyName()+wasteType)) {
//                   SewageWarningConfig sewageWarningConfig = new SewageWarningConfig();
//                   sewageWarningConfig.setCompanyName(comCompany.getCompanyName());
//                   sewageWarningConfig.setCompanyId(comCompany.getId());
//                   sewageWarningConfig.setMonitorHexavalentChromium("1");
//                   sewageWarningConfig.setMonitorTotalNickel("1");
//                   sewageWarningConfig.setMonitorTotalChromium("1");
//                   sewageWarningConfig.setWasteWaterType(wasteType);
//                   sewageWarningConfig.setHexavalentChromiumThreshold(new BigDecimal(10));
//                   sewageWarningConfig.setTotalNickelThreshold(new BigDecimal(30));
//                   sewageWarningConfig.setTotalChromiumThreshold(new BigDecimal(20));
//                   sewageWarningConfig.setParkId("1001");
//                   sewageWarningConfig.setDelFlag("0");
//                   sewageWarningConfigService.save(sewageWarningConfig);
//                   companySet.add(comCompany.getCompanyName()+wasteType);
//               }
//           }
       }
//        for (WarningDataExcel data : dataList) {
//            // 这里可以添加数据校验逻辑
//            validateData(data);
//
//            // 这里可以添加数据处理逻辑
//            processWarningData(data);
//        }
        
        log.info("{}条预警数据处理完成", dataList.size());
//        dataList.clear();
    }

    /**
     * 数据校验
     */
    private void validateData(WarningDataExcel data) {
        if (data.getCompanyName() == null || data.getCompanyName().trim().isEmpty()) {
            log.warn("企业名称不能为空");
        }
        
        if (data.getDetectionFactor() == null || data.getDetectionFactor().trim().isEmpty()) {
            log.warn("检测因子不能为空");
        }
        
        if (data.getContent() == null) {
            log.warn("含量不能为空");
        }
        
//        if (data.getContent() != null && data.getContent().compareTo(BigDecimal.ZERO) < 0) {
//            log.warn("含量不能为负数: {}", data.getContent());
//        }
    }

    /**
     * 处理预警数据
     */
    private void processWarningData(WarningDataExcel data) {
        // 根据预警等级进行不同处理
//        String warningLevel = data.getWarningLevel();
//        if (warningLevel != null) {
//            switch (warningLevel.toUpperCase()) {
//                case "一级":
//                case "1":
//                    log.warn("一级预警: 企业[{}]的[{}]含量超标，当前值: {}{}",
//                        data.getCompanyName(), data.getDetectionFactor(),
//                        data.getContent(), data.getUnit());
//                    break;
//                case "二级":
//                case "2":
//                    log.warn("二级预警: 企业[{}]的[{}]含量接近限值，当前值: {}{}",
//                        data.getCompanyName(), data.getDetectionFactor(),
//                        data.getContent(), data.getUnit());
//                    break;
//                case "三级":
//                case "3":
//                    log.info("三级预警: 企业[{}]的[{}]含量正常，当前值: {}{}",
//                        data.getCompanyName(), data.getDetectionFactor(),
//                        data.getContent(), data.getUnit());
//                    break;
//                default:
//                    log.info("未知预警等级: {}", warningLevel);
//                    break;
//            }
//        }

        // 这里可以添加其他业务逻辑，比如：
        // 1. 发送预警通知
        // 2. 记录预警历史
        // 3. 触发相关流程
    }

    /**
     * 获取总处理数量
     */
    private int getTotalCount() {
        return dataList.size();
    }
}
